package com.yinbw.oracle.config;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class SqlLoggerInterceptor implements InnerInterceptor {

//    private static final Logger log = LoggerFactory.getLogger(SqlLoggerInterceptor.class);

    @Override
    public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
        try {
            BoundSql boundSql = sh.getBoundSql();
            String sql = boundSql.getSql();
            Object parameterObject = boundSql.getParameterObject();
            List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();

            // 获取参数值列表
            List<Object> paramValues = new ArrayList<>();
            if (parameterObject != null) {
                MetaObject metaObject = SystemMetaObject.forObject(parameterObject);
                for (ParameterMapping mapping : parameterMappings) {
                    String propertyName = mapping.getProperty();
                    if ("mybatis_plus_first".equals(propertyName)){
                        break;
                    }
                    Object value = metaObject.getValue(propertyName);
                    paramValues.add(value);
                }
            }

            // 格式化SQL并记录日志
            String completeSql = formatSql(sql, paramValues);
//        log.debug("Executing  SQL: {}", completeSql);
            System.out.println("Executing  SQL：" + completeSql);
        } catch (Exception e) {
            System.out.println("Executing  SQL：Sql解析异常！");
        }
    }

    /**
     * 将参数值嵌入到SQL中
     */
    private String formatSql(String sql, List<Object> params) {
        if (params == null || params.isEmpty()) {
            return sql;
        }
        StringBuilder sb = new StringBuilder();
        int index = 0;
        int paramIndex = 0;
        while (index < sql.length()) {
            char c = sql.charAt(index);
            if (c == '?' && paramIndex < params.size()) {
                Object param = params.get(paramIndex++);
                sb.append(formatParameter(param));
            } else {
                sb.append(c);
            }
            index++;
        }
        String s = sb.toString();
        String s2 = s.replaceAll("\n", "");
        return s2;
    }

    /**
     * 格式化参数值（处理字符串、日期等）
     */
    private String formatParameter(Object param) {
        if (param == null) {
            return "null";
        }
        if (param instanceof String) {
            return "'" + param + "'";
        }
        if (param instanceof Date) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return "'" + sdf.format((Date) param) + "'";
        }
        if (param instanceof LocalDate) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 定义日期格式
            String localDateStr = ((LocalDate) param).format(formatter); // 将LocalDate转换为String
            return "'" + localDateStr + "'";
        }
        if (param instanceof LocalDateTime) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String localDateTimeStr = ((LocalDateTime) param).format(formatter);
            return "'" + localDateTimeStr + "'";
        }
        return param.toString();
    }
}